<!DOCTYPE html>


<html lang="zh-CN">


<head>
  <meta charset="utf-8" />
    
  <meta name="description" content="welcome" />
  
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    Spring Batch 批处理 |  ChenyyのBlog
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">
  
<link rel="stylesheet" href="/css/custom.css">

  
  <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
  
  

  

</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-framework/Spring Batch 批处理"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  Spring Batch 批处理
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2021/05/05/framework/Spring%20Batch%20%E6%89%B9%E5%A4%84%E7%90%86/" class="article-date">
  <time datetime="2021-05-05T02:21:58.000Z" itemprop="datePublished">2021-05-05</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E6%A1%86%E6%9E%B6/">框架</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">6.7k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">28 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <ul>
<li>简介</li>
<li>Job任务<ul>
<li>JobInstance任务实例</li>
<li>JobParameters任务参数</li>
<li>JobExceution任务执行</li>
<li>Job任务嵌套</li>
<li>JobExecutionListener任务监听</li>
</ul>
</li>
</ul>
<ul>
<li><p>Step步骤</p>
<ul>
<li>StepExecution步骤执行</li>
<li>Flow步骤流程</li>
<li>ItemReader数据读取</li>
<li>ItemWriter数据写入</li>
<li>ItemProcessor数据处理</li>
<li>ItemStream数据异常处理</li>
<li>容错机制</li>
</ul>
</li>
<li><p>ExecutionContext执行上下文</p>
</li>
<li><p>JobRepository任务仓库</p>
</li>
<li><p>JobLauncher任务启动器</p>
<ul>
<li>JobOperator任务操作</li>
</ul>
</li>
</ul>
<span id="more"></span>

<h1 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h1><p>Spring Batch 是一款基于 Spring 的企业批处理框架。</p>
<p>提供了统一的读写接口、丰富的任务处理方式、灵活的事务管理及并发处理，同时还支持日志、监控、任务重启与跳过等特性，大大简化了批处理应用开发。</p>
<ul>
<li><p>Spring Batch把批处理简化为Job和Job step两部分。</p>
</li>
<li><p>Job step中，把数据处理分为读数据(Reader)、处理数据(Processor)、写数据（Writer）三个步骤。</p>
</li>
<li><p>异常处理机制分为跳过、重试、重启三种。</p>
</li>
<li><p>作业方式分为多线程、并行、远程、分区四种。</p>
</li>
</ul>
<p><img src="https://gitee.com/chenyy-2017/pic/raw/master/note/SpringBatch%E6%B5%81%E7%A8%8B%E5%9B%BE202105051300.jpg"></p>
<h2 id="优势"><a href="#优势" class="headerlink" title="优势"></a>优势</h2><ul>
<li>开箱即用组件，包括各种资源的读、写。支持文本、XML、数据库、JMS队列等。</li>
<li>面向chunk处理。支持多次读、一次写、避免多次对资源的写入，大幅提升批处理效率。</li>
<li>事务管理能力。默认采用Spring提供的声明式事务管理模型，面向Chunk的操作支持事务管理，同时支持为每个tasklet操作设置细粒度的事务配置：隔离级别、传播行为、超时设置等。</li>
<li>元数据管理。自动记录Job和Step的执行情况、包括成功、失败、失败的异常信息、执行次数、重试次数、跳过次数、执行时间等，方便后期的维护和查看。</li>
<li>易监控的批处理应用。提供了灵活的监控模式，包括数据库、API、JMX控制台等。</li>
<li>丰富的流程定义。支持顺序任务、条件分支任务、基于这两种任务可以组织复杂的任务流程。</li>
<li>健壮的批处理应用。支持作业的跳过、重试、重启能力、避免因错误导致批处理作业的异常中断。</li>
<li>易扩展的批处理应用。扩展机制包括多线程执行一个Step(Multithreaded step)、多线程并行执行多个Step(Parallelizing step)、远程执行作业（Remote chunking）、分区执行（partitioning step）。</li>
<li>复用企业现有IT资产。提供多种Adapter能力，使得企业现有的服务可以方便集成到批处理应用中。避免重新开发、达到复用企业遗留的服务资产。</li>
</ul>
<h2 id="核心概念"><a href="#核心概念" class="headerlink" title="核心概念"></a>核心概念</h2><p>1、Job：一个接口，由多个Step组成。</p>
<p>2、JobInstance：Job的一个实例，可重复执行，每一次执行就是一个JobExceution。</p>
<p>3、JobParameters：启动、标识Job的参数。</p>
<p>4、JobExceution：执行同一个JobInstance第一次失败第二次成功，产生两个JobExceution。</p>
<p>5、Step:主要分为两块</p>
<p>（1）Tasklet：任务单元，可重复利用。接口唯一方法execute()。</p>
<p>（2）Chunk：数据块，定义多大的数据量。Chunk不断循环读数据，处理数据，然后写数据。<br>·itemReader：数据输入，每次读取一个条目；<br>·itemProcessor：数据处理；<br>·ItemWriter：数据输出，每次输出一个条目；</p>
<p>6、StepExecution：Step的每一次执行。</p>
<p>7、ExecutionContext：执行上下文，对每一个JobExecution及StepExecution的执行进行在持久化管理。</p>
<p>8、JobLauncher：启动和加载Job的接口，根据传入的参数启动，返回Job一次执行的情况。</p>
<p>9、JobRepository：Job的运行结果和状态、Step的运行结果和状态，都会保存在JobRepository中。</p>
<table>
<thead>
<tr>
<th align="center">领域对象</th>
<th align="left">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center">JobRepository</td>
<td align="left">作业仓库，保存Job、Step执行过程中的状态及结果</td>
</tr>
<tr>
<td align="center">JobLauncher</td>
<td align="left">作业执行器，是执行Job的入口</td>
</tr>
<tr>
<td align="center">Job</td>
<td align="left">一个批处理任务，由一个或多个Step组成</td>
</tr>
<tr>
<td align="center">Step</td>
<td align="left">一个任务的具体的执行逻辑单位</td>
</tr>
<tr>
<td align="center">Item</td>
<td align="left">一条数据记录</td>
</tr>
<tr>
<td align="center">ItemReader</td>
<td align="left">从数据源读数据</td>
</tr>
<tr>
<td align="center">ItemProcessor</td>
<td align="left">对数据进行处理，如数据清洗、转换、过滤、校验等</td>
</tr>
<tr>
<td align="center">ItemWriter</td>
<td align="left">写入数据到指定目标</td>
</tr>
<tr>
<td align="center">Chunk</td>
<td align="left">给定数量的Item集合，如读取到chunk数量后，才进行写操作</td>
</tr>
<tr>
<td align="center">Tasklet</td>
<td align="left">Step中具体执行逻辑，可重复执行</td>
</tr>
</tbody></table>
<p><img src="https://gitee.com/chenyy-2017/pic/raw/master/note/SpringBatch.jpg"></p>
<p>数据表</p>
<p><img src="https://gitee.com/chenyy-2017/pic/raw/master/note/20210505094728.png"></p>
<h1 id="Job任务"><a href="#Job任务" class="headerlink" title="Job任务"></a>Job任务</h1><p>Job是封装一个批处理过程的实体，可以通过XML或Java类配置，可以简单的将Job理解为是每一步（Step）实例的容器。</p>
<p>他结合了多个Step，为它们提供统一的服务同时也为Step提供个性化的服务，比如步骤重启。通常情况下Job的配置包含以下内容：</p>
<ul>
<li>Job的名称</li>
<li>定义和排序Step执行实例。</li>
<li>标记每个Step是否可以重启。</li>
</ul>
<p>Spring Batch为Job接口提供了默认的实现——SimpleJob，其中实现了一些标准的批处理方法。下面的代码展示了如可注入一个Job。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">@Bean</span><br><span class="line">public Job testJob() &#123;</span><br><span class="line">    return this.jobBuilderFactory.get(&quot;testJob&quot;) //get中命名了Job的名称</span><br><span class="line">                     .start(stepOne())  </span><br><span class="line">                     .next(stepTwo())</span><br><span class="line">                     .next(stepThree())</span><br><span class="line">                     .end()</span><br><span class="line">                     .build();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>




<h2 id="JobInstance任务实例"><a href="#JobInstance任务实例" class="headerlink" title="JobInstance任务实例"></a>JobInstance任务实例</h2><p>JobInstance是指批处理作业运行的实例。同一个JobInstance具有相同的上下文（ExecutionContext内容见后文）。</p>
<p>例如一个批处理必须在每天执行一次，系统在2019年5月1日执行了一次我们称之为2019-05-01的实例，类似的还会有2019-05-02、2019-05-03实例。</p>
<h2 id="JobParameters任务参数"><a href="#JobParameters任务参数" class="headerlink" title="JobParameters任务参数"></a>JobParameters任务参数</h2><p>前面讨论了JobInstance与Job的区别，但是具体的区别内容都是通过JobParameters体现的。一个JobParameters对象中包含了一系列Job运行相关的参数，这些参数可以用于参考或者用于实际的业务使用。对应的关系如下图：</p>
<p><img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9ncmFwaC5iYWlkdS5jb20vcmVzb3VyY2UvMjIyNGEwNGE3NTYzNjk0YThhZjYzMDE1ODMyMDI2NjMucG5n?x-oss-process=image/format,png" alt="file"></p>
<p>当我们执行2个不同的JobInstance时JobParameters中的属性都会有差异。可以简单的认为一个JobInstance的标识就是Job+JobParameters。</p>
<h2 id="JobExecution任务执行"><a href="#JobExecution任务执行" class="headerlink" title="JobExecution任务执行"></a>JobExecution任务执行</h2><p>JobExecution可以理解为单次运行Job的容器。一次JobInstance执行的结果可能是成功、也可能是失败。</p>
<p>例如2019-05-01执行了一次JobInstance，但是执行的过程失败，因此第二次还会有一个“相同的”的JobInstance被执行。</p>
<p>Job用于定义批处理如何执行，JobInstance纯粹的就是一个处理对象，把所有的运行内容和信息组织在一起，主要是为了当面临问题时定义正确的重启参数。而JobExecution是运行时的“容器”，记录动态运行时的各种属性和上线文。</p>
<p>他包括的信息有：</p>
<table>
<thead>
<tr>
<th align="center">属性</th>
<th align="center">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="center">status</td>
<td align="center">状态类名为BatchStatus，它指示了执行的状态。在执行的过程中状态为BatchStatus#STARTED，失败：BatchStatus#FAILED，完成：BatchStatus#COMPLETED</td>
</tr>
<tr>
<td align="center">startTime</td>
<td align="center">java.util.Date对象，标记批处理任务启动的系统时间，批处理任务未启动数据为空</td>
</tr>
<tr>
<td align="center">endTime</td>
<td align="center">java.util.Date对象，结束时间无论是否成功都包含该数据，如未处理完为空</td>
</tr>
<tr>
<td align="center">exitStatus</td>
<td align="center">ExitStatus类，记录运行结果。</td>
</tr>
<tr>
<td align="center">createTime</td>
<td align="center">java.util.Date,JobExecution的创建时间，某些使用execution已经创建但是并未开始运行。</td>
</tr>
<tr>
<td align="center">lastUpdate</td>
<td align="center">java.util.Date，最后一次更新时间</td>
</tr>
<tr>
<td align="center">executionContext</td>
<td align="center">批处理任务执行的所有用户数据</td>
</tr>
<tr>
<td align="center">failureExceptions</td>
<td align="center">记录在执行Job时的异常，对于排查问题非常有用</td>
</tr>
</tbody></table>
<p>以上这些内容Spring Batch都会通过JobRepository进行持久化（这些信息官方文成称之为MetaData），因此在对应的数据源中可以看到下列信息：</p>
<p>BATCH_JOB_INSTANCE：</p>
<table>
<thead>
<tr>
<th align="center">JOB_INST_ID</th>
<th align="center">JOB_NAME</th>
</tr>
</thead>
<tbody><tr>
<td align="center">1</td>
<td align="center">EndOfDayJob</td>
</tr>
</tbody></table>
<p>BATCH_JOB_EXECUTION_PARAMS：</p>
<table>
<thead>
<tr>
<th align="center">JOB_EXECUTION_ID</th>
<th align="center">TYPE_CD</th>
<th>KEY_NAME</th>
<th>DATE_VAL</th>
<th>IDENTIFYING</th>
</tr>
</thead>
<tbody><tr>
<td align="center">1</td>
<td align="center">DATE</td>
<td>schedule.Date</td>
<td>2019-01-01</td>
<td>TRUE</td>
</tr>
</tbody></table>
<p>BATCH_JOB_EXECUTION：</p>
<table>
<thead>
<tr>
<th align="center">JOB_EXEC_ID</th>
<th align="center">JOB_INST_ID</th>
<th>START_TIME</th>
<th>END_TIME</th>
<th>STATUS</th>
</tr>
</thead>
<tbody><tr>
<td align="center">1</td>
<td align="center">1</td>
<td>2019-01-01 21:00</td>
<td>2017-01-01 21:30</td>
<td>FAILED</td>
</tr>
</tbody></table>
<p>当某个Job批处理任务失败之后会在对应的数据库表中路对应的状态。假设1月1号执行的任务失败，技术团队花费了大量的时间解决这个问题到了第二天才继续执行这个任务。</p>
<p>BATCH_JOB_INSTANCE：</p>
<table>
<thead>
<tr>
<th align="center">JOB_INST_ID</th>
<th align="center">JOB_NAME</th>
</tr>
</thead>
<tbody><tr>
<td align="center">1</td>
<td align="center">EndOfDayJob</td>
</tr>
<tr>
<td align="center">2</td>
<td align="center">EndOfDayJob</td>
</tr>
</tbody></table>
<p>BATCH_JOB_EXECUTION_PARAMS：</p>
<table>
<thead>
<tr>
<th align="center">JOB_EXECUTION_ID</th>
<th align="center">TYPE_CD</th>
<th>KEY_NAME</th>
<th>DATE_VAL</th>
<th>IDENTIFYING</th>
</tr>
</thead>
<tbody><tr>
<td align="center">1</td>
<td align="center">DATE</td>
<td>schedule.Date</td>
<td>2019-01-01</td>
<td>TRUE</td>
</tr>
<tr>
<td align="center">2</td>
<td align="center">DATE</td>
<td>schedule.Date</td>
<td>2019-01-01</td>
<td>TRUE</td>
</tr>
<tr>
<td align="center">3</td>
<td align="center">DATE</td>
<td>schedule.Date</td>
<td>2019-01-02</td>
<td>TRUE</td>
</tr>
</tbody></table>
<p>BATCH_JOB_EXECUTION：</p>
<table>
<thead>
<tr>
<th align="center">JOB_EXEC_ID</th>
<th align="center">JOB_INST_ID</th>
<th>START_TIME</th>
<th>END_TIME</th>
<th>STATUS</th>
</tr>
</thead>
<tbody><tr>
<td align="center">1</td>
<td align="center">1</td>
<td>2019-01-01 21:00</td>
<td>2017-01-01 21:30</td>
<td>FAILED</td>
</tr>
<tr>
<td align="center">2</td>
<td align="center">1</td>
<td>2019-01-02 21:00</td>
<td>2017-01-02 21:30</td>
<td>COMPLETED</td>
</tr>
<tr>
<td align="center">3</td>
<td align="center">2</td>
<td>2019-01-02 21:31</td>
<td>2017-01-02 22:29</td>
<td>COMPLETED</td>
</tr>
</tbody></table>
<p>从数据上看好似JobInstance是一个接一个顺序执行的，但是对于Spring Batch并没有进行任何控制。不同的JobInstance很有可能是同时在运行（相同的JobInstance同时运行会抛出JobExecutionAlreadyRunningException异常）。</p>
<h2 id="Job的嵌套"><a href="#Job的嵌套" class="headerlink" title="Job的嵌套"></a>Job的嵌套</h2><p> 某些情况下，一个job需要嵌套执行另一个job，此时需要借助step。在一个step中嵌套执行一个子job，然后在父job中执行这个嵌套的step即可。</p>
<p>1.job可以嵌套使用，嵌套的Job我们将其称为子job,被嵌套的Job我们将其称为父job;</p>
<p>2.一个父Job可以有多个子Job;</p>
<p>3.子job不能单独运行，需要其父Job去启动;</p>
<p><img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9ncmFwaC5iYWlkdS5jb20vcmVzb3VyY2UvMjIyYjIzN2E1NGE0NWMyZmYyMmNkMDE1ODMyMjI1NDQucG5n?x-oss-process=image/format,png" alt="file"></p>
<h2 id="JobExecutionListener任务监听"><a href="#JobExecutionListener任务监听" class="headerlink" title="JobExecutionListener任务监听"></a>JobExecutionListener任务监听</h2><p>当任务执行完毕或开始执行时，需要执行一些处理工作，从job级别到item级别都有。</p>
<p>可以实现JobExecutionListener接口，还可以用 @BeforeJob 和 @AfterJob 注解实现监听器。</p>
<p>添加方式：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">@Bean</span><br><span class="line">public Job footballJob() &#123;</span><br><span class="line">    return this.jobBuilderFactory.get(&quot;footballJob&quot;)</span><br><span class="line">                     .listener(sampleListener()) //JobExecutionListener的实现类</span><br><span class="line">                     ...</span><br><span class="line">                     .build();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h1 id="Step步骤"><a href="#Step步骤" class="headerlink" title="Step步骤"></a>Step步骤</h1><p>Step是批处理重复运行的最小单元，它按照顺序定义了一次执行的必要过程。</p>
<p>与JobExecution的概念类似，Step也有特定的StepExecution，关系结构如下：</p>
<p><img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9ncmFwaC5iYWlkdS5jb20vcmVzb3VyY2UvMjIyMDEzMDk5YjQ2OGEwYzFjYmVmMDE1ODMyMDMyNTAucG5n?x-oss-process=image/format,png" alt="file"></p>
<h2 id="StepExecution步骤实例"><a href="#StepExecution步骤实例" class="headerlink" title="StepExecution步骤实例"></a>StepExecution步骤实例</h2><p>StepExecution表示单次执行Step的容器，每次Step执行时都会有一个新的StepExecution被创建。与JobExecution不同的是，当某个Step执行失败后默认并不会重新执行。StepExecution包含以下属性：</p>
<table>
<thead>
<tr>
<th align="center">属性</th>
<th align="center">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="center">status</td>
<td align="center">状态类名为BatchStatus，它指示了执行的状态。在执行的过程中状态为BatchStatus#STARTED，失败：BatchStatus#FAILED，完成：BatchStatus#COMPLETED</td>
</tr>
<tr>
<td align="center">startTime</td>
<td align="center">java.util.Date对象，标记StepExecution启动的系统时间，未启动数据为空</td>
</tr>
<tr>
<td align="center">endTime</td>
<td align="center">java.util.Date对象，结束时间，无论是否成功都包含该数据，如未处理完为空</td>
</tr>
<tr>
<td align="center">exitStatus</td>
<td align="center">ExitStatus类，记录运行结果。</td>
</tr>
<tr>
<td align="center">createTime</td>
<td align="center">java.util.Date,JobExecution的创建时间，某些使用execution已经创建但是并未开始运行。</td>
</tr>
<tr>
<td align="center">lastUpdate</td>
<td align="center">java.util.Date，最后一次更新时间</td>
</tr>
<tr>
<td align="center">executionContext</td>
<td align="center">批处理任务执行的所有用户数据</td>
</tr>
<tr>
<td align="center">readCount</td>
<td align="center">成功读取数据的次数</td>
</tr>
<tr>
<td align="center">wirteCount</td>
<td align="center">成功写入数据的次数</td>
</tr>
<tr>
<td align="center">commitCount</td>
<td align="center">成功提交数据的次数</td>
</tr>
<tr>
<td align="center">rollbackCount</td>
<td align="center">回归数据的次数，有业务代码触发</td>
</tr>
<tr>
<td align="center">readSkipCount</td>
<td align="center">当读数据发生错误时跳过处理的次数</td>
</tr>
<tr>
<td align="center">processSkipCount</td>
<td align="center">当处理过程发生错误，跳过处理的次数</td>
</tr>
<tr>
<td align="center">filterCount</td>
<td align="center">被过滤规则拦截未处理的次数</td>
</tr>
<tr>
<td align="center">writeSkipCount</td>
<td align="center">写数据失败，跳过处理的次数</td>
</tr>
</tbody></table>
<h2 id="Flow步骤流程"><a href="#Flow步骤流程" class="headerlink" title="Flow步骤流程"></a>Flow步骤流程</h2><p>Step 是一个独立的、顺序的处理步骤，包含完整的输入、处理以及输出。但是在企业应用中，我们面对的更多情况是多个步骤按照一定的顺序进行处理。因此如何维护步骤之间的执行顺序是我们需要考虑的。Spring Batch 提供了 Step Flow 来解决这个问题。</p>
<p>Flow有以下特点：</p>
<ol>
<li>   flow是一个Step的集合，他规定了Step与Step之间的转换关系;</li>
<li>   创建Flow可以达到复用的效果，让其在不同的Job之间进行复用;</li>
<li>   使用FlowBuilder去创建一个Flow,他和Job类似，使用start(),next()以及end()来运行flow;</li>
</ol>
<h3 id="顺序Flow"><a href="#顺序Flow" class="headerlink" title="顺序Flow"></a>顺序Flow</h3> <figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">// 创建Flow对象,指明Flow对象包含哪些Step</span><br><span class="line">@Bean</span><br><span class="line">    public Flow jobFlowDemoFlow1()&#123;</span><br><span class="line">        return new FlowBuilder&lt;Flow&gt;(&quot;jobFlowDemoFlow1&quot;)</span><br><span class="line">                .start(jobFlowDemoTwoStep1())</span><br><span class="line">                .next(jobFlowDemoTwoStep2())</span><br><span class="line">                .build();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">@Bean</span><br><span class="line">    public Job jobFlowDemo()&#123;</span><br><span class="line">        return jobBuilderFactory.get(&quot;jobFlowDemo&quot;)</span><br><span class="line">                .start(jobFlowDemoFlow1()).end()</span><br><span class="line">                .build();</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>



<h3 id="Decider决策器"><a href="#Decider决策器" class="headerlink" title="Decider决策器"></a>Decider决策器</h3><p>动态自定义Decider决定Flow 执行顺序，为我们提供下一步执行哪一个Step提供条件决策。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">** 自定义一个MyDecider。</span><br><span class="line">** 根据调用次数，基数返回“EVEN”，偶数返回“ODD”；</span><br><span class="line">**/</span><br><span class="line">public class MyDecider implements JobExecutionDecider &#123;</span><br><span class="line">    private int count = 0;</span><br><span class="line">    @Override</span><br><span class="line">    public FlowExecutionStatus decide(JobExecution jobExecution, StepExecution stepExecution) &#123;</span><br><span class="line">        count ++;</span><br><span class="line">        if (count % 2 == 0)</span><br><span class="line">            return new FlowExecutionStatus(&quot;EVEN&quot;);</span><br><span class="line">        else</span><br><span class="line">            return new FlowExecutionStatus(&quot;ODD&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">    </span><br><span class="line">	/**</span><br><span class="line">	** job中调用MyDecider。</span><br><span class="line">	** 当返回“EVEN”时，调用evenStep；当返回“ODD”时，调用oddStep。</span><br><span class="line">	**/</span><br><span class="line">    @Bean</span><br><span class="line">    public Job flowDecisonDemoJob()&#123;</span><br><span class="line">        return jobBuilderFactory.get(&quot;flowDecisonDemoJob&quot;).start(firstStep())</span><br><span class="line">                .next(myDecider())</span><br><span class="line">                .from(myDecider()).on(&quot;EVEN&quot;).to(evenStep())</span><br><span class="line">                .from(myDecider()).on(&quot;ODD&quot;).to(oddStep())</span><br><span class="line">                .from(oddStep()).on(&quot;*&quot;).to(myDecider())</span><br><span class="line">                .end()</span><br><span class="line">                .build();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    @Bean</span><br><span class="line">    public Step oddStep()&#123;</span><br><span class="line">        return stepBuilderFactory.get(&quot;oddStep&quot;)</span><br><span class="line">                .tasklet(((stepContribution, chunkContext) -&gt; &#123;</span><br><span class="line">                    System.out.println(&quot;oddStep&quot;);</span><br><span class="line">                    return RepeatStatus.FINISHED;</span><br><span class="line">                &#125;)).build();</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    @Bean</span><br><span class="line">    public Step evenStep()&#123;</span><br><span class="line">        return stepBuilderFactory.get(&quot;evenStep&quot;)</span><br><span class="line">                .tasklet(((stepContribution, chunkContext) -&gt; &#123;</span><br><span class="line">                    System.out.println(&quot;evenStep&quot;);</span><br><span class="line">                    return RepeatStatus.FINISHED;</span><br><span class="line">                &#125;)).build();</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    @Bean</span><br><span class="line">    public JobExecutionDecider myDecider()&#123;</span><br><span class="line">        return new MyDecider();</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>





<h3 id="Split并行处理"><a href="#Split并行处理" class="headerlink" title="Split并行处理"></a>Split并行处理</h3><p>当遇到数据量比较大或者每个ITEM处理耗时的时候，能够并行处理是很重要的。并行处理的时候一般经历Split-Partitioned-Merge的过程</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line">@Bean</span><br><span class="line">public Job readandwritedbJob() &#123;</span><br><span class="line">    Flow flow1 = new FlowBuilder&lt;SimpleFlow&gt;(&quot;asyncFlow1&quot;).start(step2()).build();</span><br><span class="line">    Flow flow2 = new FlowBuilder&lt;SimpleFlow&gt;(&quot;asyncFlow2&quot;).start(step3()).build();</span><br><span class="line">    return jobBuilderFactory.get(&quot;readandwritedbJob&quot;)</span><br><span class="line">            .incrementer(new RunIdIncrementer())</span><br><span class="line">            .flow(step1())</span><br><span class="line">            .split(new SimpleAsyncTaskExecutor()).add(flow1,flow2)</span><br><span class="line">            .end()</span><br><span class="line">            .build();</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line">@Bean</span><br><span class="line">public Tasklet tasklet1() &#123;</span><br><span class="line">    return new ReadAndWriteDbTask();</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line">@Bean</span><br><span class="line">public Tasklet tasklet2() &#123;</span><br><span class="line">    return new ReadAndWriteDbTask2();</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line">@Bean</span><br><span class="line">public Tasklet tasklet3() &#123;</span><br><span class="line">    return new ReadAndWriteDbTask3();</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line">@Bean</span><br><span class="line">public Step step1() &#123;</span><br><span class="line">    return stepBuilderFactory.get(&quot;step1&quot;)</span><br><span class="line">            .tasklet(tasklet1())</span><br><span class="line">            .build();</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line">@Bean</span><br><span class="line">public Step step2() &#123;</span><br><span class="line">    return stepBuilderFactory.get(&quot;step2&quot;)</span><br><span class="line">            .tasklet(tasklet2())</span><br><span class="line">            .build();</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line">@Bean</span><br><span class="line">public Step step3() &#123;</span><br><span class="line">    return stepBuilderFactory.get(&quot;step3&quot;)</span><br><span class="line">            .tasklet(tasklet3())</span><br><span class="line">            .build();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="ItemReader数据读取"><a href="#ItemReader数据读取" class="headerlink" title="ItemReader数据读取"></a>ItemReader数据读取</h2><p>提供数据的接口，只有一个方法read()。它读取一个数据并且移动到下一个数据上去，在读取结束时必须返回一个null，否则表明数据没有读取完毕。</p>
<p>提供的默认实现有33个之多，基本涵盖所有的数据源读取类型。支持从数据库/文本/xml/多个文件读取数据。</p>
<p>2.在这个接口中只有一个方法read(),它读取一个数据并且移动到下一个数据上去，在读取结束时必须返回一个null,否则表明数据没有读取完毕;</p>
<p>接口定义如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">public interface ItemReader&lt;T&gt; &#123; @Nullable T read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException;&#125;</span><br></pre></td></tr></table></figure>



<p>示例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">** 使用JdbcPagingItemReader从数据库读取数据</span><br><span class="line">**/</span><br><span class="line">@Configuration</span><br><span class="line">public class DBJdbcDemoJobConfiguration &#123;</span><br><span class="line">    @Autowired</span><br><span class="line">    private JobBuilderFactory jobBuilderFactory;</span><br><span class="line"> </span><br><span class="line">    @Autowired</span><br><span class="line">    private StepBuilderFactory stepBuilderFactory;</span><br><span class="line"> </span><br><span class="line">    @Autowired</span><br><span class="line">    @Qualifier(&quot;dbJdbcDemoWriter&quot;)</span><br><span class="line">    private ItemWriter&lt;? super Customer&gt; dbJdbcDemoWriter;</span><br><span class="line"> </span><br><span class="line">    @Autowired</span><br><span class="line">    private DataSource dataSource;</span><br><span class="line"> </span><br><span class="line">    @Bean</span><br><span class="line">    public Job DBJdbcDemoJob()&#123;</span><br><span class="line">        return jobBuilderFactory.get(&quot;DBJdbcDemoJob&quot;)</span><br><span class="line">                .start(dbJdbcDemoStep())</span><br><span class="line">                .build();</span><br><span class="line"> </span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    @Bean</span><br><span class="line">    public Step dbJdbcDemoStep() &#123;</span><br><span class="line">        return stepBuilderFactory.get(&quot;dbJdbcDemoStep&quot;)</span><br><span class="line">                .&lt;Customer,Customer&gt;chunk(100)</span><br><span class="line">                .reader(dbJdbcDemoReader())</span><br><span class="line">                .writer(dbJdbcDemoWriter)</span><br><span class="line">                .build();</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    @Bean</span><br><span class="line">    @StepScope</span><br><span class="line">    public JdbcPagingItemReader&lt;Customer&gt; dbJdbcDemoReader() &#123;</span><br><span class="line">        JdbcPagingItemReader&lt;Customer&gt; reader = new JdbcPagingItemReader&lt;&gt;();</span><br><span class="line"> </span><br><span class="line">        reader.setDataSource(this.dataSource);</span><br><span class="line">        reader.setFetchSize(100); //批量读取</span><br><span class="line">        reader.setRowMapper((rs,rowNum)-&gt;&#123;</span><br><span class="line">				    // 讲读取的记录转化为对象</span><br><span class="line">            return Customer.builder().id(rs.getLong(&quot;id&quot;))</span><br><span class="line">                    .firstName(rs.getString(&quot;firstName&quot;))</span><br><span class="line">                    .lastName(rs.getString(&quot;lastName&quot;))</span><br><span class="line">                    .birthdate(rs.getString(&quot;birthdate&quot;))</span><br><span class="line">                    .build();</span><br><span class="line"> </span><br><span class="line">        &#125;);</span><br><span class="line"> </span><br><span class="line">        // 指定sql语句</span><br><span class="line">        MySqlPagingQueryProvider queryProvider = new MySqlPagingQueryProvider();</span><br><span class="line">        queryProvider.setSelectClause(&quot;id, firstName, lastName, birthdate&quot;);</span><br><span class="line">        queryProvider.setFromClause(&quot;from Customer&quot;);</span><br><span class="line">        // 指定字段排序</span><br><span class="line">        Map&lt;String, Order&gt; sortKeys = new HashMap&lt;&gt;(1);</span><br><span class="line">        sortKeys.put(&quot;id&quot;, Order.ASCENDING);</span><br><span class="line">        queryProvider.setSortKeys(sortKeys);</span><br><span class="line"> </span><br><span class="line">        reader.setQueryProvider(queryProvider);</span><br><span class="line"> </span><br><span class="line">        return reader;</span><br><span class="line"> </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line">** 指定输出方法</span><br><span class="line">**/</span><br><span class="line">@Component(&quot;dbJdbcDemoWriter&quot;)</span><br><span class="line">public class DbJdbcDemoWriter implements ItemWriter&lt;Customer&gt; &#123;</span><br><span class="line">    @Override</span><br><span class="line">    public void write(List&lt;? extends Customer&gt; items) throws Exception &#123;</span><br><span class="line">        for (Customer customer:items)</span><br><span class="line">            System.out.println(customer);</span><br><span class="line"> </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="ItemWriter数据写入"><a href="#ItemWriter数据写入" class="headerlink" title="ItemWriter数据写入"></a>ItemWriter数据写入</h2><p>对于read读取数据时是以一条数据为单位，每条数据是一个item的循环读取，而对于writer写入数据则是以chunk为单位，一块一块的进行写入。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">** 写入数据库JdbcBatchItemWriter</span><br><span class="line">**/</span><br><span class="line">@Configuration</span><br><span class="line">public class DbOutputDemoJobWriterConfiguration &#123;</span><br><span class="line"> </span><br><span class="line">    @Autowired</span><br><span class="line">    public DataSource dataSource;</span><br><span class="line"> </span><br><span class="line">    @Bean</span><br><span class="line">    public JdbcBatchItemWriter&lt;Customer&gt; dbOutputDemoJobFlatFileWriter()&#123;</span><br><span class="line">        JdbcBatchItemWriter&lt;Customer&gt; itemWriter = new JdbcBatchItemWriter&lt;&gt;();</span><br><span class="line">		// 设置数据源</span><br><span class="line">        itemWriter.setDataSource(dataSource);</span><br><span class="line">		// 执行sql语句</span><br><span class="line">        itemWriter.setSql(&quot;insert into customer(id,firstName,lastName,birthdate) values &quot; +</span><br><span class="line">                &quot;(:id,:firstName,:lastName,:birthdate)&quot;);</span><br><span class="line">		// 替换属性值</span><br><span class="line">        itemWriter.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider&lt;&gt;());</span><br><span class="line">        return itemWriter;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="ItemProcessor数据处理"><a href="#ItemProcessor数据处理" class="headerlink" title="ItemProcessor数据处理"></a>ItemProcessor数据处理</h2><p>主要用于实现业务逻辑，验证，过滤等。</p>
<p>提供ItemProcessor&lt;I,O&gt;这个接口，参数item是ItemReader读取到的数据，返回O是交给ItemWriter写的数据。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public interface ItemProcessor&lt;I, O&gt; &#123;</span><br><span class="line">    O process(I item) throws Exception;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>具体ItemProcessor实现</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">@Component</span><br><span class="line">public class IdFilterProcessor implements ItemProcessor&lt;Customer,Customer&gt; &#123;</span><br><span class="line">    @Override</span><br><span class="line">    public Customer process(Customer item) throws Exception &#123;</span><br><span class="line">		// 保留id为偶数的数据</span><br><span class="line">        if (item.getId() % 2 == 0)&#123;</span><br><span class="line">            // 并将FirstName转大写</span><br><span class="line">        	return new Customer(</span><br><span class="line">                item.getId(),</span><br><span class="line">                item.getFirstName().toUpperCase(),</span><br><span class="line">                item.getLastName(),</span><br><span class="line">                item.getBirthdate()</span><br><span class="line">            );</span><br><span class="line">        &#125;</span><br><span class="line">		// 过滤id为基数的数据</span><br><span class="line">        else &#123;</span><br><span class="line">            return null;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="ItemStream数据异常处理"><a href="#ItemStream数据异常处理" class="headerlink" title="ItemStream数据异常处理"></a>ItemStream数据异常处理</h2><p>对于chunk类型的Step，通过ItemStream接口管理它的状态，ItemStream接口：</p>
<p>2.状态的管理是来实现的</p>
<p>3.ItemStream接口：</p>
<p>（1）open():每一次step执行会调用</p>
<p>（2）Update():每一个chunk去执行都会调用</p>
<p>（3）Close():所有的chunk执行完毕会调用</p>
<p><img src="https://gitee.com/chenyy-2017/pic/raw/master/note/20210505112354.png"></p>
<p><strong>构造例子</strong></p>
<p> 准备个cvs文件，在第33条数据，添加一条错误名字信息 ；当读取到这条数据时，抛出异常终止程序。</p>
<p><img src="https://gitee.com/chenyy-2017/pic/raw/master/note/20210505112612.png"></p>
<p><strong>ItemReader测试代码</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br></pre></td><td class="code"><pre><span class="line">@Component(&quot;restartItemReader&quot;)</span><br><span class="line">// 实现ItemStreamReader，等同于同时实现了ItemStream、ItemReader</span><br><span class="line">public class RestartItemReader implements ItemStreamReader&lt;CustomerInfo&gt; &#123;</span><br><span class="line"></span><br><span class="line">    // 记录当前读取的行数</span><br><span class="line">    private Long curLine = 0L;</span><br><span class="line">    // 重启状态初始值</span><br><span class="line">    private boolean restart = false;</span><br><span class="line">    // 持久化信息到数据库</span><br><span class="line">    private ExecutionContext executionContext;</span><br><span class="line"></span><br><span class="line">    private FlatFileItemReader&lt;CustomerInfo&gt; reader = new FlatFileItemReader&lt;&gt;();</span><br><span class="line"></span><br><span class="line">    // 构造器,读取文件的相关配置</span><br><span class="line">    public RestartItemReader() &#123;</span><br><span class="line">        System.out.println(&quot;-------------Constructor run ......&quot;);</span><br><span class="line">        reader.setResource(new ClassPathResource(&quot;customer_info.csv&quot;));</span><br><span class="line">        DefaultLineMapper&lt;CustomerInfo&gt; lineMapper = new DefaultLineMapper&lt;&gt;();</span><br><span class="line">        DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();</span><br><span class="line">        tokenizer.setNames(new String[]&#123;&quot;CustomerID&quot;, &quot;CustomerName&quot;, &quot;CertType&quot;, &quot;CertID&quot;&#125;);</span><br><span class="line">        lineMapper.setLineTokenizer(tokenizer);</span><br><span class="line">        lineMapper.setFieldSetMapper(fieldSet -&gt;</span><br><span class="line">            CustomerInfo.builder()</span><br><span class="line">                    .customerID(fieldSet.readString(&quot;CustomerID&quot;))</span><br><span class="line">                    .customerName(fieldSet.readString(&quot;CustomerName&quot;))</span><br><span class="line">                    .certType(fieldSet.readString(&quot;CertType&quot;))</span><br><span class="line">                    .certID(fieldSet.readString(&quot;CertID&quot;))</span><br><span class="line">                    .build()</span><br><span class="line">        );</span><br><span class="line">        lineMapper.afterPropertiesSet();</span><br><span class="line">        reader.setLineMapper(lineMapper);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    // ItemReader的抽象方法实现</span><br><span class="line">    public CustomerInfo read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException &#123;</span><br><span class="line">        CustomerInfo customerInfo = null;</span><br><span class="line">        this.curLine ++;</span><br><span class="line"></span><br><span class="line">        if(curLine == 1L) &#123;</span><br><span class="line">            reader.setLinesToSkip(1);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        //如果是重启，则从上一步读取的行数继续往下执行</span><br><span class="line">        if(restart) &#123;</span><br><span class="line">            reader.setLinesToSkip(this.curLine.intValue());</span><br><span class="line">            restart = false;</span><br><span class="line">            System.out.println(&quot;Start reading from &quot; + this.curLine);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        reader.open(this.executionContext);</span><br><span class="line"></span><br><span class="line">        customerInfo = reader.read();</span><br><span class="line">        //当匹配到wrongName时，显示抛出异常，终止程序</span><br><span class="line">        if(customerInfo != null) &#123;</span><br><span class="line">            if(customerInfo.getFirstName().equals(&quot;wrongName&quot;)) &#123;</span><br><span class="line">                throw new RuntimeException(&quot;Something wrong. CustomerID: &quot; + customerInfo.getId());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            curLine--;</span><br><span class="line">        &#125;</span><br><span class="line">        return  customerInfo;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    // ItemStream的open方法。在chunk前执行</span><br><span class="line">    public void open(ExecutionContext executionContext) throws ItemStreamException &#123;</span><br><span class="line">        this.executionContext = executionContext;</span><br><span class="line">		// 如果是重启job，从数据库读取重启的行数，从重启行数开始重新执行</span><br><span class="line">        if(executionContext.containsKey(&quot;curLine&quot;)) &#123;</span><br><span class="line">            // 从executionContext中获取数据（executionContext中的数据为SpringBatch自动从数据库中读取的最近一次执行时存入的变量）</span><br><span class="line">            this.curLine = executionContext.getLong(&quot;curLine&quot;);</span><br><span class="line">            this.restart = true;</span><br><span class="line">        &#125;</span><br><span class="line">		// 如果不是重启job，初始化行数，从第一行开始执行</span><br><span class="line">        else &#123;</span><br><span class="line">            this.curLine = 0L;</span><br><span class="line">            // 向executionContext中存入变量</span><br><span class="line">            executionContext.put(&quot;curLine&quot;, this.curLine.longValue());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    // 每个chunk之后执行</span><br><span class="line">    public void update(ExecutionContext executionContext) throws ItemStreamException &#123;</span><br><span class="line">		// 每执行完一个批次chunk，打印当前行数</span><br><span class="line">        System.out.println(&quot;Update CurLine: &quot; + this.curLine);</span><br><span class="line">         // 向executionContext中存入变量</span><br><span class="line">        executionContext.put(&quot;curLine&quot;, this.curLine.longValue());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    // 所有chunk都执行完之后执行</span><br><span class="line">    public void close() throws ItemStreamException &#123;</span><br><span class="line">        System.out.println(&quot;chunk close.&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>Job配置</strong></p>
<p>以10条记录为一个批次，进行读取</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">@Configuration</span><br><span class="line">public class RestartDemoJobConfiguration &#123;</span><br><span class="line">    @Autowired</span><br><span class="line">    private JobBuilderFactory jobBuilderFactory;</span><br><span class="line"> </span><br><span class="line">    @Autowired</span><br><span class="line">    private StepBuilderFactory stepBuilderFactory;</span><br><span class="line"> </span><br><span class="line">    @Autowired</span><br><span class="line">    @Qualifier(&quot;flatFileDemoWriter&quot;)</span><br><span class="line">    private ItemWriter&lt;? super Customer&gt; flatFileDemoWriter;</span><br><span class="line"> </span><br><span class="line">    @Autowired</span><br><span class="line">    @Qualifier(&quot;restartDemoReader&quot;)</span><br><span class="line">    private ItemReader&lt;Customer&gt; restartDemoReader;</span><br><span class="line"> </span><br><span class="line">    @Bean</span><br><span class="line">    public Job restartDemoJob()&#123;</span><br><span class="line">        return jobBuilderFactory.get(&quot;restartDemoJob&quot;)</span><br><span class="line">                .start(restartDemoStep())</span><br><span class="line">                .build();</span><br><span class="line"> </span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    @Bean</span><br><span class="line">    public Step restartDemoStep() &#123;</span><br><span class="line">        return stepBuilderFactory.get(&quot;restartDemoStep&quot;)</span><br><span class="line">                .&lt;Customer,Customer&gt;chunk(10)</span><br><span class="line">                .reader(restartDemoReader)</span><br><span class="line">                .writer(flatFileDemoWriter)</span><br><span class="line">                .build();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当第一次执行时，程序在33行抛出异常异常，curline值是30；</p>
<p><img src="https://gitee.com/chenyy-2017/pic/raw/master/note/20210505112851.png"></p>
<p>这时，可以查询数据库 batch_step_excution表，发现curline值已经以 键值对形式，持久化进数据库（上文以10条数据为一个批次；故33条数据异常时，curline值为30）</p>
<p><img src="https://gitee.com/chenyy-2017/pic/raw/master/note/20210505112921.png"></p>
<p>接下来，更新wrongName，再次执行程序；</p>
<p>程序会执行open方法，判断数据库step中map是否存在curline，如果存在，则是重跑，即读取curline，从该批次开始往下继续执行；</p>
<p><img src="https://gitee.com/chenyy-2017/pic/raw/master/note/20210505113007.png"></p>
<h2 id="容错机制"><a href="#容错机制" class="headerlink" title="容错机制"></a>容错机制</h2><ul>
<li>restart是针对job来使用，是重启job的一个操作。默认情况下，当任务出现异常时，SpringBatch会结束任务，当使用相同参数重启任务时，SpringBatch会去执行未执行的剩余任务。</li>
<li>retry是对job的某一step而言，处理一条数据item的时候发现有异常，则重试一次该数据item的step的操作。</li>
<li>skip是对job的某一个step而言，处理一条数据item的时候发现有异常，则跳过该数据item的step的操作。</li>
</ul>
<p><strong>retry示例</strong></p>
<p>设置允许重试的次数为3次，允许跳过的数据最多为1条，如果job失败了，运行重跑次数最多为3次：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">@Bean</span><br><span class="line">public Step stepForTranscation(StepBuilderFactory stepBuilderFactory,@Qualifier(&quot;stepForTranscationReader&quot;)ListItemReader&lt;String&gt; reader,@Qualifier(&quot;stepForTranscationProcessor&quot;)ItemProcessor&lt;String, String&gt; processor,@Qualifier(&quot;stepForTranscationWriter&quot;)ItemWriter&lt;String&gt; writer) &#123;</span><br><span class="line">    return stepBuilderFactory.get(&quot;stepForTranscation&quot;)</span><br><span class="line">            .&lt;String, String&gt; chunk(3)</span><br><span class="line">            .reader(reader)</span><br><span class="line">            .processor(processor)</span><br><span class="line">            .writer(writer)</span><br><span class="line">			// 容错方法</span><br><span class="line">			.faultTolerant()</span><br><span class="line">			// 重试次数</span><br><span class="line">			.retryLimit(3)</span><br><span class="line">			// 出现该异常时重试			</span><br><span class="line">			.retry(DataIntegrityViolationException.class)</span><br><span class="line">			// 跳过次数</span><br><span class="line">			.skipLimit(1)</span><br><span class="line">			// 出现该异常时跳过	</span><br><span class="line">			.skip(DataIntegrityViolationException.class)</span><br><span class="line">			// 跳过错误监听器</span><br><span class="line">			.listener(mySkipListener)</span><br><span class="line">			// 重启次数</span><br><span class="line">			.startLimit(3)</span><br><span class="line">            .build();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>skip示例</strong></p>
<p>skip后面配置跳过错误的监听器SkipListener</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">public class MySkipListener implements SkipListener&lt;String, String&gt;&#123;</span><br><span class="line">	// 发生读操作跳过错误时，需要执行的监听</span><br><span class="line">	public void onSkipInRead(Throwable t)&#123;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	// 发生写操作跳过错误时，需要执行的监听</span><br><span class="line">	public void onSkipInWrite(String item, Throwable t)&#123;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	// 处理数据时跳过错误时，需要执行的监听</span><br><span class="line">	public void onSkipInProcess (String item, Throwable t)&#123;</span><br><span class="line">		System.out.println(item + &quot;occur exception&quot; + t);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>




<h1 id="ExecutionContext执行上下文"><a href="#ExecutionContext执行上下文" class="headerlink" title="ExecutionContext执行上下文"></a>ExecutionContext执行上下文</h1><p>ExecutionContext提供了一个Key/Value机制，在StepExecution和JobExecution对象的任何位置都可以获取到ExecutionContext中的任何数据。最有价值的作用是记录数据的执行位置，以便发生重启时候从对应的位置继续执行：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">executionContext.putLong(getKey(LINES_READ_COUNT), reader.getPosition())</span><br></pre></td></tr></table></figure>


<p>比如在任务中有一个名为“loadData”的Step，他的作用是从文件中读取数据写入到数据库，当第一次执行失败后，数据库中有如下数据：</p>
<p>BATCH_JOB_INSTANCE：</p>
<table>
<thead>
<tr>
<th align="center">JOB_INST_ID</th>
<th align="center">JOB_NAME</th>
</tr>
</thead>
<tbody><tr>
<td align="center">1</td>
<td align="center">EndOfDayJob</td>
</tr>
</tbody></table>
<p>BATCH_JOB_EXECUTION_PARAMS：</p>
<table>
<thead>
<tr>
<th align="center">JOB_INST_ID</th>
<th align="center">TYPE_CD</th>
<th>KEY_NAME</th>
<th>DATE_VAL</th>
</tr>
</thead>
<tbody><tr>
<td align="center">1</td>
<td align="center">DATE</td>
<td>schedule.Date</td>
<td>2019-01-01</td>
</tr>
</tbody></table>
<p>BATCH_JOB_EXECUTION：</p>
<table>
<thead>
<tr>
<th align="center">JOB_EXEC_ID</th>
<th align="center">JOB_INST_ID</th>
<th>START_TIME</th>
<th>END_TIME</th>
<th>STATUS</th>
</tr>
</thead>
<tbody><tr>
<td align="center">1</td>
<td align="center">1</td>
<td>2017-01-01 21:00</td>
<td>2017-01-01 21:30</td>
<td>FAILED</td>
</tr>
</tbody></table>
<p>BATCH_STEP_EXECUTION：</p>
<table>
<thead>
<tr>
<th align="center">STEP_EXEC_ID</th>
<th align="center">JOB_EXEC_ID</th>
<th>STEP_NAME</th>
<th>START_TIME</th>
<th>END_TIME</th>
<th>STATUS</th>
</tr>
</thead>
<tbody><tr>
<td align="center">1</td>
<td align="center">1</td>
<td>loadData</td>
<td>2017-01-01 21:00</td>
<td>2017-01-01 21:30</td>
<td>FAILED</td>
</tr>
</tbody></table>
<p>BATCH_STEP_EXECUTION_CONTEXT： </p>
<table>
<thead>
<tr>
<th align="center">STEP_EXEC_ID</th>
<th align="center">SHORT_CONTEXT</th>
</tr>
</thead>
<tbody><tr>
<td align="center">1</td>
<td align="center">{piece.count=40321}</td>
</tr>
</tbody></table>
<p>在上面的例子中，Step运行30分钟处理了40321个“pieces”，我们姑且认为“pieces”表示行间的行数（实际就是每个Step完成循环处理的个数）。</p>
<p>这个值会在每个commit之前被更新记录在ExecutionContext中（更新需要用到StepListener后文会详细说明）。</p>
<p>当我们再次重启这个Job时并记录在BATCH_STEP_EXECUTION_CONTEXT中的数据会加载到ExecutionContext中,这样当我们继续执行批处理任务时可以从上一次中断的位置继续处理。</p>
<p>例如下面的代码在ItemReader中检查上次执行的结果，并从中断的位置继续执行：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">if (executionContext.containsKey(getKey(LINES_READ_COUNT))) &#123;</span><br><span class="line">    log.debug(&quot;Initializing for restart. Restart data is: &quot; + executionContext);</span><br><span class="line"></span><br><span class="line">    long lineCount = executionContext.getLong(getKey(LINES_READ_COUNT));</span><br><span class="line"></span><br><span class="line">    LineReader reader = getReader();</span><br><span class="line"></span><br><span class="line">    Object record = &quot;&quot;;</span><br><span class="line">    while (reader.getPosition() &lt; lineCount &amp;&amp; record != null) &#123;</span><br><span class="line">        record = readLine();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>ExecutionContext是根据JobInstance进行管理的，因此只要是相同的实例都会具备相同的ExecutionContext（无论是否停止）。此外通过以下方法都可以获得一个ExecutionContext：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ExecutionContext ecStep = stepExecution.getExecutionContext();</span><br><span class="line">ExecutionContext ecJob = jobExecution.getExecutionContext();</span><br></pre></td></tr></table></figure>

<p>但是这2个ExecutionContext并不相同，前者是在一个Step中每次Commit数据之间共享，后者是在Step与Step之间共享。</p>
<h1 id="JobRepository任务仓库（持久化）"><a href="#JobRepository任务仓库（持久化）" class="headerlink" title="JobRepository任务仓库（持久化）"></a>JobRepository任务仓库（持久化）</h1><p>JobRepository是所有前面介绍的对象实例的持久化机制。他为JobLauncher、Job、Step的实现提供了CRUD操作。当一个Job第一次被启动时，一个JobExecution会从数据源中获取到，同时在执行的过程中StepExecution、JobExecution的实现都会记录到数据源中。使用@EnableBatchProcessing注解后JobRepository会进行自动化配置。</p>
<h1 id="JobLauncher任务启动器"><a href="#JobLauncher任务启动器" class="headerlink" title="JobLauncher任务启动器"></a>JobLauncher任务启动器</h1><p>JobLauncher为Job的启动运行提供了一个边界的入口，在启动Job的同时还可以定制JobParameters：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">public interface JobLauncher &#123;</span><br><span class="line">	public JobExecution run(Job job, JobParameters jobParameters)</span><br><span class="line">				throws JobExecutionAlreadyRunningException, JobRestartException,</span><br><span class="line">					   JobInstanceAlreadyCompleteException, JobParametersInvalidException;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Spring Boot默认支持自动启动已配置好的Job，我们可以通过配置项<strong>spring.batch.job.enabled=false</strong>来禁止Spring容器自动启动Job。</p>
<h2 id="从web容器的HttpRequest来启动job"><a href="#从web容器的HttpRequest来启动job" class="headerlink" title="从web容器的HttpRequest来启动job"></a>从web容器的HttpRequest来启动job</h2><p>从web容器的HttpRequest来启动job，一般只是用一个 JobLauncher 来异步启动job，http请求会调用这个 JobLauncher 来启动它们需要的job。</p>
<p><img src="https://gitee.com/chenyy-2017/pic/raw/master/note/20210505115536.png"></p>
<p>通过web的API接口，传入Job的参数，去调用 JobLauncher启动Job。调用的Job根据Bean name去指定。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">@Bean</span><br><span class="line">public JobLauncher jobLauncher() &#123;</span><br><span class="line">    SimpleJobLauncher jobLauncher = new SimpleJobLauncher();</span><br><span class="line">    jobLauncher.setJobRepository(jobRepository());</span><br><span class="line">    jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor()); //转换为异步任务</span><br><span class="line">    jobLauncher.afterPropertiesSet();</span><br><span class="line">    return jobLauncher;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">@Autowired</span><br><span class="line"> private JobLauncher jobLauncher;</span><br><span class="line"> </span><br><span class="line"> @Autowired</span><br><span class="line"> private JobLauncherDemoJob jobLaunchDemoJob;</span><br><span class="line"> </span><br><span class="line"> @GetMapping(&quot;/&#123;job1param&#125;&quot;)</span><br><span class="line"> public String runJob1(@PathVariable(&quot;job1param&quot;) String job1param) throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException &#123;</span><br><span class="line">     System.out.println(&quot;Request to run job1 with param: &quot; + job1param);</span><br><span class="line">     JobParameters jobParameters = new JobParametersBuilder()</span><br><span class="line">             .addString(&quot;job1param&quot;,job1param)</span><br><span class="line">             .toJobParameters();</span><br><span class="line">     jobLauncher.run(jobLaunchDemoJob,jobParameters);</span><br><span class="line">     return &quot;Job1 success.&quot;;</span><br><span class="line"> </span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<h2 id="JobOperator启动"><a href="#JobOperator启动" class="headerlink" title="JobOperator启动"></a>JobOperator启动</h2><p>在成功创建一个job后，Spring Batch 默认在项目启动时候执行配置的job。往往在正常业务处理中，需要我们手动或者定时去触发job，所以这边便引入了jobLauncher、jobOperator两个执行器。</p>
<p>当我们通过调度器调用Job时，从命令行来启动job，会为每一个job初始化一个JVM，因此每个job会有一个自己的 JobLauncher，整个流程如下： </p>
<p><img src="https://gitee.com/chenyy-2017/pic/raw/master/note/20210505115400.png"></p>
<p><img src="https://gitee.com/chenyy-2017/pic/raw/master/note/20210505120301.png"></p>
<p>JobRepository 提供了对元数据的 CRUD 操作，JobExplorer 提供了对元数据的只读操作。</p>
<p>在Spring Batch 中JobOperator 接口提供了这些操作类，来对任务进行监测，并完成相当多的任务控制功能，比如停止、重启或对任务进行汇总。</p>
<p>通过API接口调用或者定时任务调用：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">@Controller</span><br><span class="line">public class JobOperatorController &#123;</span><br><span class="line">	@Autowired</span><br><span class="line">    private JobOperator jobOperator;</span><br><span class="line"></span><br><span class="line">	//不需要注入Job对象</span><br><span class="line">    //@Autowired</span><br><span class="line">    //JobLauncherDemoJob jobLauncherDemoJob;</span><br><span class="line"> </span><br><span class="line">    @GetMapping(&quot;/&#123;job2param&#125;&quot;)</span><br><span class="line">    public String runJob1(@PathVariable(&quot;job2param&quot;) String job2param) throws Exception &#123;</span><br><span class="line">        System.out.println(&quot;Request to run job2 with param: &quot; + job2param);</span><br><span class="line">        jobOperator.start(&quot;jobOperatorDemoJob&quot;,&quot;job2param=&quot;+job2param);</span><br><span class="line">        return &quot;Job2 success.&quot;;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    /**</span><br><span class="line">    ** 定时任务调用，通过corn表达式，满足条件时候，即执行</span><br><span class="line">    **/</span><br><span class="line">    @Scheduled(fixedDelay = 5000)</span><br><span class="line">    public void scheduler() throws JobInstanceAlreadyCompleteException, JobExecutionAlreadyRunningException, JobParametersInvalidException, JobRestartException, JobParametersNotFoundException, NoSuchJobException &#123;</span><br><span class="line">        jobOperator().startNextInstance(&quot;jobScheduledDemoJob&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>JobOperator执行Job</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br></pre></td><td class="code"><pre><span class="line">public class JobOperatorDemo implements StepExecutionListener,ApplicationContextAware&#123;</span><br><span class="line">    @Autowired</span><br><span class="line">    private JobBuilderFactory jobBuilderFactory;</span><br><span class="line">    @Autowired</span><br><span class="line">    private StepBuilderFactory stepBuilderFactory;</span><br><span class="line">    @Autowired</span><br><span class="line">	private Map&lt;String,JobParameters&gt; parameters;</span><br><span class="line">	@Autowired</span><br><span class="line">    private JobRepository jobRepository; </span><br><span class="line">    @Autowired</span><br><span class="line">    private JobExplorer jobExplorer;</span><br><span class="line">    @Autowired</span><br><span class="line">    private JobRegistry jobRegistry;</span><br><span class="line">    @Autowired</span><br><span class="line">    private JobLauncher jobLauncher;</span><br><span class="line">	//@Autowired</span><br><span class="line">	pricate ApplicationContext context;</span><br><span class="line">		 </span><br><span class="line">	@Bean</span><br><span class="line">	public JobRepositoryBeanPostProcessor jobRegistrar() throws Exception&#123;</span><br><span class="line">		JobRepositoryBeanPostProcessor postProcessor = new JobRepositoryBeanPostProcessor;</span><br><span class="line">		postProcessor.setJobRegistry(jobRegistry);</span><br><span class="line">		postProcessor.setBeanFactory(context.getAutowireCapableBeanFactory());</span><br><span class="line">		postProcessor.afterPropertiesSet();</span><br><span class="line">		return postProcessor;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	@Bean</span><br><span class="line">    public JobOperator jobOperator()&#123;</span><br><span class="line">        SimpleJobOperator operator = new SimpleJobOperator();</span><br><span class="line">        operator.setJobLauncher(jobLauncher);</span><br><span class="line">		// 参数转换</span><br><span class="line">        operator.setJobParametersConverter(new DefaultJobParametersConverter());</span><br><span class="line">        // 持久化方式</span><br><span class="line">        operator.setJobRepository(jobRepository);</span><br><span class="line">        // 任务相关信息</span><br><span class="line">        operator.setJobExplorer(jobExplorer);</span><br><span class="line">        // 注册：任务名字符串和任务对象关联</span><br><span class="line">        operator.setJobRegistry(jobRegistry);</span><br><span class="line">        return operator;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    @Bean</span><br><span class="line">    public Job jobOperatorDemo() &#123;</span><br><span class="line">        return jobBuilderFactory.get(&quot;jobOperatorDemo&quot;)</span><br><span class="line">				.listener(this)</span><br><span class="line">                .start(jobOperatorDemoStep())</span><br><span class="line">                .build();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">	@Bean</span><br><span class="line">    public Step jobOperatorDemoStep() &#123;</span><br><span class="line">        return stepBuilderFactory.get(&quot;jobOperatorDemoStep&quot;)</span><br><span class="line">                .tasklet(new Tasklet() &#123;</span><br><span class="line">                    @Override</span><br><span class="line">                    public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception &#123;</span><br><span class="line">                        System.out.println(&quot;jobOperatorDemoStep，msg： &quot;+parameter.get(&quot;job2param&quot;).getValue());</span><br><span class="line">                        return RepeatStatus.FINISHED;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;).build();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">	public void beforeStep(StepExecution stepExcution)&#123;</span><br><span class="line">		parameter = stepExcution.getJobParameters().getParameters();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">	public void setApplicationContext(ApplicationContext applicationContext)&#123;</span><br><span class="line">		this.context = applicationContext;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<p>参考：</p>
<p>官网：<a target="_blank" rel="noopener" href="https://spring.io/projects/spring-batch">https://spring.io/projects/spring-batch</a></p>
<p>Spring Batch 批处理（1） - 简介及使用场景：<a target="_blank" rel="noopener" href="https://chenchenchen.blog.csdn.net/article/details/104764027">https://chenchenchen.blog.csdn.net/article/details/104764027</a></p>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          打赏
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2021/05/05/framework/Spring%20Batch%20%E6%89%B9%E5%A4%84%E7%90%86/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E6%A1%86%E6%9E%B6/" rel="tag">框架</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2021/05/09/resource/finance/E%E5%A4%A7%E7%9A%84%E6%8A%95%E8%B5%84%E7%AC%94%E8%AE%B0/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            E大的投资笔记：资产配置
          
        </div>
      </a>
    
    
      <a href="/2021/05/03/Mysql/Mysql%E9%94%81/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">Mysql锁</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "",
    app_key: "",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
   
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2021
        <i class="ri-heart-fill heart_icon"></i> Chenyy
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="ChenyyのBlog"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">文章</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/book">收藏</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about/me">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="搜索">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
  </div>
</body>

</html>